package cn.assumejson.springframework.beans.factory.support;

import cn.assumejson.springframework.beans.factory.BeanFactory;
import cn.assumejson.springframework.beans.factory.BeansException;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

/**
 * cglib 实现
 *
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/11/30 8:54
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName) throws ClassNotFoundException {
        return instantiate(bd, beanName, null);
    }

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, Constructor<?> ctor, Object... args) throws ClassNotFoundException {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(bd.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        if (null == ctor) return enhancer.create();
        return enhancer.create(ctor.getParameterTypes(), args);
    }
}
